package com.ruiyun.app.lib.wxshare

import android.content.Context
import android.graphics.Bitmap
import android.text.TextUtils
import android.widget.Toast
import com.ruiyun.app.lib.wxshare.interfaces.ShareType
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram
import com.tencent.mm.opensdk.modelmsg.*
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage.IMediaObject
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import java.io.ByteArrayOutputStream


class WxShareManager {

    private lateinit var api: IWXAPI
    private lateinit var mContext: Context
    private var isshare = true
    fun init(context: Context, appid: String?) {
        mContext = context
        api = WXAPIFactory.createWXAPI(mContext, appid)
    }

    companion object {
        private var wxToastManager: WxShareManager? = null
        fun getInstance(): WxShareManager {
            return if (wxToastManager == null) {
                synchronized(WxShareManager::class.java) {
                    if (wxToastManager == null) {
                        wxToastManager = WxShareManager()
                    }
                    return wxToastManager!!
                }
            } else {
                wxToastManager!!
            }
        }
    }


    /**
     * 发起微信登录请求
     */
    fun WxLogin() {
        val req = SendAuth.Req()
        req.scope = "snsapi_userinfo"
        req.state = "wx_login_ry"
        sendReq(req)
    }

    fun sendReq(req: BaseReq?) {
        if (api != null && req != null) api!!.sendReq(req) else Toast.makeText(mContext, "微信分享初始化失败", Toast.LENGTH_LONG).show()
    }

    /**
     * 分享图片
     *
     * @param qrResult
     */
    fun ShareImage(image: Bitmap?, qrResult: ShareBean?) {
        if (image == null) return
        isshare = true
        val imageObj = WXImageObject(image)
        sendReq(qrResult, imageObj, "img")
    }

    /**
     * 分享文本
     */
    fun ShareText(text: String?, qrResult: ShareBean?) {
        isshare = true
        val textObj = WXTextObject()
        textObj.text = text
        sendReq(qrResult, textObj, "text")
    }

    /**
     * 分享Web
     */
    fun ShareWeb(webpageUrl: String?, qrResult: ShareBean?) {
        isshare = true
        val webpage = WXWebpageObject()
        webpage.webpageUrl = webpageUrl
        sendReq(qrResult, webpage, "webpage")
    }

    /**
     * 分享视频
     */
    fun ShareVideo(webpageUrl: String?, qrResult: ShareBean?) {
        isshare = true
        val webpage = WXVideoObject()
        webpage.videoUrl = webpageUrl
        sendReq(qrResult, webpage, "video")
    }

    /**
     * 调起微信小程序
     */
    fun upMiniprogram(userName: String?) {
        //  IWXAPI api = WXAPIFactory.createWXAPI(mContext, appId);
        val req = WXLaunchMiniProgram.Req()
        req.userName = userName // 填小程序原始id
        //  req.path = "拉起小程序页面的可带参路径";                  //拉起小程序页面的可带参路径，不填默认拉起小程序首页
        req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE // 可选打开 开发版，体验版和正式版
        sendReq(req)
    }

    /**
     * 分享小程序
     *
     * @param userName 小程序原始id
     * @param path     小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
     */
    fun shareProgram(userName: String?, path: String?, webpageUrl: String?, shareBean: ShareBean?) {
        if (!TextUtils.isEmpty(userName) && shareBean != null) {
            val miniProgram = WXMiniProgramObject()
            miniProgram.webpageUrl = webpageUrl
            miniProgram.userName = userName //小程序端提供参数
            miniProgram.path = path //小程序端提供参数
            miniProgram.miniprogramType = WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE
            shareBean.shareType = ShareType.WXSceneSession
            sendReq(shareBean, miniProgram, "miniProgram")
        }
    }

    /**
     * 分享非小程序
     *
     * @param shareBean
     * @param iMediaObject
     * @param tag
     */
    fun sendReq(shareBean: ShareBean?, iMediaObject: IMediaObject?, tag: String?) {
        if (shareBean != null && iMediaObject != null && isshare) {
            val req = SendMessageToWX.Req()
            val msg = WXMediaMessage(iMediaObject)
            req.transaction = buildTransaction(tag)
            req.scene = shareBean.shareType
            msg.title = shareBean.shareTitle
            msg.description = shareBean.description
            if (shareBean.thumbData != null) msg.thumbData = bmpToByteArray(shareBean.thumbData, true)
            req.message = msg
            sendReq(req)
            isshare = false
        }
    }

    /**
     * 图片转换成byte
     *
     * @param bmp
     * @param needRecycle
     * @return
     */
    private fun bmpToByteArray(bmp: Bitmap?, needRecycle: Boolean): ByteArray? {
        val output = ByteArrayOutputStream()
        bmp!!.compress(Bitmap.CompressFormat.PNG, 100, output)
        if (needRecycle) {
            bmp.recycle()
        }
        val result: ByteArray = output.toByteArray()
        try {
            output.close()
        } catch (e: Exception) {
        }
        return result
    }

    /**
     * @param type
     * @return
     */
    private fun buildTransaction(type: String?): String? {
        return if (type == null) System.currentTimeMillis().toString() else type + System.currentTimeMillis()
    }

    /**
     * 判断是否安装了微信客户端
     *
     * @return
     */
    fun isWXAppInstalled(): Boolean {
        return if (api == null) false else api!!.isWXAppInstalled
    }

    fun getApi(): IWXAPI {
        return api
    }

    fun setIsshare(isshare: Boolean) {
        this.isshare = isshare
    }
}